const jQuery = require("jquery");
const path = require('path');
const {
    allconfig
} = require(path.join(__dirname, './js/config'));



const {
    Loading,
    Message
} = require('element-ui');
const {
    ipcRenderer
} = require('electron');
const user = require('./js/user');
const qr = require("qr-image");

let loadinstance = null,
    messageinfo = null;

var code = ""; //定义全局变量

jQuery(document).ready(function ($) {

    var $form_modal = $('.cd-user-modal'),
        $form_login = $form_modal.find('#cd-login'), //账号密码登录区域
        $form_signup = $form_modal.find('#cd-signup'), //二维码登录区域
        $form_modal_tab = $('.cd-switcher'), //切换标签
        $tab_login = $form_modal_tab.children('li').eq(0).children('a'), //账号登录标签
        $tab_signup = $form_modal_tab.children('li').eq(1).children('a'), //二维码登录标签
        $submitbtn = $("#submitbtn"), //登录按钮
        $loginid = $("#signin-loginid"), //登录账号
        $pwd = $("#signup-password"), //登录密码
        $loginqr = $("#loginqr"), //登录二维码图片
        $rememberme = $('#remember-me'); //记住密码

    //读取配置文件
    console.log(allconfig);

    //获取用户是否配置记住密码
    const userremember = user.getUserConfig('rememberme');
    if (userremember) {
        doLogin(user.getUserConfig('username'), user.getUserConfig('password'), userremember);
    }

    $submitbtn.on('click', function (event) {
        event.preventDefault();

        doLogin($loginid.val(), $pwd.val(), $rememberme[0].checked);
    });


    function doLogin(username, pwd, rememberme) {
        //显示加载中
        showLoading("登录中")
        user.doLogin(username, pwd, rememberme).then((retinfo) => {
            // console.log(retinfo);
            //跳转首页
            ipcRenderer.send("loadpage", "./render/mainindex/mainindex.html");
        }).catch(msg => {
            showMessage(msg, "warning", 2000);
        });
    }

    function loginbytoken(token) {
        //显示加载中
        showLoading("登录中")
        user.doLoginbyToken(token).then((retinfo) => {
            // console.log(retinfo);
            //跳转首页
            ipcRenderer.send("loadpage", "./render/mainindex/mainindex.html");
        }).catch(msg => {
            showMessage(msg, "warning", 2000);
        });;
    }

    //switch from a tab to another
    $form_modal_tab.on('click', function (event) {
        event.preventDefault();
        ($(event.target).is($tab_login)) ? login_selected(): signup_selected();
    });




    function login_selected() {
        $form_login.addClass('is-selected');
        $form_signup.removeClass('is-selected');
        $tab_login.addClass('selected');
        $tab_signup.removeClass('selected');
    }


    //默认二维码登录，账号密码登录太危险
    signup_selected();

    function signup_selected() {
        $form_login.removeClass('is-selected');
        $form_signup.addClass('is-selected');
        $tab_login.removeClass('selected');
        $tab_signup.addClass('selected');

        //显示二维码
        code = uuid();
        var loginqr = qr.imageSync(allconfig.serverurl + "/frame/pages/login/mobile/mobileconfirmlogin.html?code=" + code, {
            type: 'svg',
            size: 6
        })
        


        // var pipe = loginqr.pipe(require('fs').createWriteStream('loginqr.png'));
        // pipe.on('finish', function () {
        // });
        $loginqr.attr("src", 'data:image/svg+xml;base64,' + Buffer(loginqr).toString('base64'));
    }


    //迁移框架的扫码轮询逻辑
    var qrSwitch = true,
        pollcount = 0;

    longPolling();


    function longPolling() {
        qrcreatetime = FormatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        orderStr = $('#scansuccess').hasClass("hidden") ? "query" : "login";

        if (orderStr != null && qrSwitch && pollcount < 50) {
            qrSwitch = false;
            $.ajax({
                url: allconfig.serverurl + "/rest/toolsqrloginaction/qrLoginQuery?isCommondto=true",
                data: {
                    "code": code,
                    "time": qrcreatetime,
                    "order": orderStr
                },
                timeout: 6000,
                //dataType : "text",
                type: "POST",
                success: function (data, textStatus) {
                    // console.log(data);
                    var customstr = JSON.parse(data).custom;
                    // console.log(customstr);
                    if (customstr) {
                        var custom = JSON.parse(customstr);
                        var invalid = custom.invalid;
                        var scanned = custom.scanned;
                        var token = custom.token;
                        if (invalid === false &&
                            scanned === true) {
                            //模糊处理
                            $loginqr.addClass("blur");
                            $('#scansuccess').removeClass("hidden");
                            qrcreatetime = null;
                            setTimeout(longPolling, 1000);
                        } else if (token && token.length > 0) {
                            loginbytoken(token);
                        } else {
                            setTimeout(longPolling, 1000);
                        }
                    }
                    pollcount++;

                },
                complete: function () {
                    qrSwitch = true;
                }
            });
        } else {
            $('#scansuccess').addClass("hidden");
            $('#scantimeout').removeClass("hidden");
            //模糊处理
            $loginqr.addClass("blur");
        }
    }

    // 日期格式化
    function FormatDate(date, fmt) { //author: meizz   
        var o = {
            "M+": date.getMonth() + 1, //月份   
            "d+": date.getDate(), //日   
            "H+": date.getHours(), //小时   
            "m+": date.getMinutes(), //分   
            "s+": date.getSeconds(), //秒   
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
            //毫秒   
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1,
                    (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k])
                        .substr(("" + o[k]).length)));
        return fmt;
    }
});


function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");

    return uuid;
}

function showLoading(info, time) {
    closeMessage();
    closeLoading();
    loadinstance = Loading.service({
        target: ".cd-user-modal-container",
        fullscreen: true,
        text: info
    });
    if (time) {
        setTimeout(function () {
            closeLoading();
        }, time)
    }
}

function closeLoading() {
    if (loadinstance) {
        loadinstance.close();
    }
}

function showMessage(info, type, time) {
    closeMessage();
    closeLoading();
    messageinfo = Message({
        message: info,
        type: type,
        duration: time
    });
}

function closeMessage() {
    if (messageinfo) {
        Message.closeAll();
    }
}
